import sqlite3 from 'sqlite3';
import logger from "./logger4js";

export class DBHelper {
  constructor() {
    this.db = new sqlite3.Database("./sqlite3.test.db", err => {
      if(err) {
        logger.error(err);
      }
    });
  }

  getDB(dbName) {
    let me = this;
    return new Promise((resolve, reject) => {
      me.db = new sqlite3.Database(dbName, function(err) {
        if (err) {
          reject(new Error(err));
        }
        resolve();
      });
    });
  }

  createTable(sql) {
    let me = this;
    return new Promise((resolve, reject) => {
      me.db.exec(sql, function(err) {
        if (err) {
          reject(new Error(err));
        }
        resolve();
      });
    });
  }
  all(sql, param) {
    return this.sql(sql, param, "all");
  }
  sql(sql, param, mode) {
    let me = this;
    mode = mode == "all" ? "all" : mode == "get" ? "get" : "run";
    logger.debug("MODE>" + mode);
    return new Promise((resolve, reject) => {
      me.db[mode](sql, param, function(err, data) {
        logger.debug("SQL>" + sql);
        logger.debug("PARAM>" + param);
        if (err) {
          reject(new Error(err));
        } else {
          if (data) {
            resolve(data);
          } else {
            resolve("success");
          }
        }
      });
    });
  }
}
export default new DBHelper;

